//
//  UILabel+ZZUtil.m
//  OCFrame
//
//  Created by hfzhangzhang on 2017/4/12.
//  Copyright © 2017年 hfzhangzhang. All rights reserved.
//

#import "UILabel+ZZUtil.h"


@implementation UILabel (ZZUtil)

+ (UILabel *)zz_createLabelWithText:(NSString *)text Font:(UIFont *)font
{
    
    UILabel *lable =[[UILabel alloc]init];
    
    return lable;
}

@end

@implementation UILabel (size)

-(void)zz_setLineSpacing:(float)space width:(CGFloat)width
{
    if (space < 0.01 || !self.text) {
        return;
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text];
    [attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, [self.text length])];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    self.height  = [self fixWidthFrame:self.width font:self.font lineSpacing:space].size.height;
    if (self.height> self.font.lineHeight) {
        [paragraphStyle setLineSpacing:space];
    }
    else{
    }
    [paragraphStyle setLineBreakMode:NSLineBreakByCharWrapping];
    [paragraphStyle setAlignment:self.textAlignment];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attributedString;
    
}

- (CGRect)fixWidthFrame:(CGFloat)width font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing
{
    CGSize size =  CGSizeMake(width, MAXFLOAT);
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.text.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.text.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];
    
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:self.text]) {  //如果包含中文,中文高度适配有点小问题，需要处理
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    return rect;
}

//判断如果包含中文
- (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}
@end

